package com.lib.ui.activity.kit;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.lib.MyApplication;
import com.lib.app.ARouterPathUtils;
import com.lib.app.EventBusTagUtils;
import com.lib.bean.Event;
import com.lib.bean.PushDetailBean;
import com.lib.fastkit.R;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.db.shared_prefrences.interfaces.UserCacheInterface;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.ui.base.control.ActivityCollector;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.px_dp.ScreenAdaptationUtil;
import com.lib.fastkit.utils.status_bar.QMUI.QMUIStatusBarHelper;
import com.lib.fastkit.views.button_deal.click.ClickUtils;
import com.lib.observer.ObserverListener;
import com.lib.observer.ObserverManager;
import com.lib.utls.pop.LiveCheckMoneyPopupUtils;
import com.lib.utls.pop.NewDaYiConnectPopupUtil;
import com.lib.utls.pop.PushPopupUtils;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * Created by Eagle510 on 2017/8/10.
 * 功能：
 * 1.Activity的固定方法流程
 * 2.状态栏的显示与隐藏
 * 3.透明状态栏
 * 4.沉静式状态栏
 * 5.标题栏的显示与隐藏
 * 6.状态栏的主题颜色修改
 * 7.Activity的管理
 * 8.日志打印与Toast打印
 * 9.键盘的显示与隐藏
 * 10.点击屏幕隐藏键盘
 * 11.启动Activity
 * 12.findViewById
 */

public abstract class BaseActivity extends AppCompatActivity {
    private Toast mToast;
    private Unbinder unbinder;

    private String className = "com.lib.ui.activity.kit.BaseActivity";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        setRequestedOrientation(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        initSystemBarTint();
        addActivity();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        //无title
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //全屏
//        getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN , WindowManager.LayoutParams. FLAG_FULLSCREEN);

        setContentView(getLayoutId());

        unbinder = ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        onCreateView();

        //友盟:在所有的Activity 的onCreate 方法或在应用的BaseActivity的onCreate方法中添加以下方法
        PushAgent.getInstance(this).onAppStart();

        Log.e("=============", "==============================================当前页面");
        Log.e("类名检测======", this.getClass().getName());
        Log.e("=============", "====================================================");

        initActivityLife();

        //设置横屏
//        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//        }

        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }

        ScreenAdaptationUtil.setCustomDensity(getApplication(), this);

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        ViewGroup decorView = (ViewGroup) getWindow().getDecorView();
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        WindowManager.LayoutParams layoutParams = (WindowManager.LayoutParams) decorView.getLayoutParams();
//旋转
//    layoutParams.rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_ROTATE;
//淡入淡出
//    layoutParams.rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_CROSSFADE;
//无动画
//    layoutParams.rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_JUMPCUT;
//无缝旋转模式
        layoutParams.rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_SEAMLESS;
        windowManager.updateViewLayout(decorView, layoutParams);

//        WindowManager.LayoutParams windowAttributes = getWindow().getAttributes();
//        windowAttributes.rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_SEAMLESS;
//        getWindow().setAttributes(windowAttributes);

    }

    @Override
    protected void onResume() {
        super.onResume();

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        MobclickAgent.onResume(this);
    }


    @Override
    protected void onPause() {
        super.onPause();

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        MobclickAgent.onPause(this);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //友盟分享
//        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    //获取布局id
    protected abstract int getLayoutId();

    //==============================================================================================
    //====================================================================Activity的固定方法流程====
    //==============================================================================================
    //Activity的管理
    private void addActivity() {
        ActivityCollector.getInstance().addActivity(this);
    }

    //Activity的操作
    protected abstract void onCreateView();
    //==============================================================================================
    //============================================================================显示与隐藏键盘====
    //==============================================================================================

    /**
     * 隐藏软键盘
     */
    public void hideSoftInput() {
        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(
                        this.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 显示软键盘
     */
    public void showSoftInput() {
        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                .toggleSoftInput(
                        InputMethodManager.RESULT_UNCHANGED_SHOWN,
                        InputMethodManager.HIDE_NOT_ALWAYS);
    }


    //==============================================================================================
    //==========================================================================处理键盘点击隐藏====
    //==============================================================================================


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FX_FOCUS_NAVIGATION_UP);
                return true;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FX_FOCUS_NAVIGATION_UP);
                return true;


        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * 设置点击屏幕隐藏键盘
     * 防止二次点击
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        if (ev.getAction() == MotionEvent.ACTION_DOWN) {

            boolean b = ClickUtils.isFastDoubleClick();
            //LogUtil.e(b + "");
            if (b) {
                return true;
            }
            // get current focus,Generally it is EditText
            View view = getCurrentFocus();
            if (isShouldHideSoftKeyBoard(view, ev)) {
                hideSoftKeyBoard(view.getWindowToken());
            }


        }

        return super.dispatchTouchEvent(ev);
    }


    /**
     * Judge what situation hide the soft keyboard,click EditText view should show soft keyboard
     *
     * @param
     * @param event
     * @return
     */
    private boolean isShouldHideSoftKeyBoard(View view, MotionEvent event) {
        if (view != null && (view instanceof EditText)) {
            int[] l = {0, 0};
            view.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + view.getHeight(), right = left
                    + view.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // If click the EditText event ,ignore it
                return false;
            } else {
                return true;
            }
        }
        // if the focus is EditText,ignore it;
        return false;
    }

    /**
     * hide soft keyboard
     *
     * @param token
     */
    private void hideSoftKeyBoard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    //==============================================================================================
    //================================================================================处理状态栏====
    //==============================================================================================

    /**
     * 设置状态栏颜色
     * 沉静式状态栏和透明状态栏只能同时存在一个
     * 默认为沉静式
     */
    protected void initSystemBarTint() {

        if (!noStatusBar()) {
            if (!translucentStatusBar()) {

                if (calmStatusBar()) {

                    QMUIStatusBarHelper.setStatusBarLightMode(this);

                }


            } else {

                /**
                 * 设置透明状态栏
                 */
                // 代表 5.0 及以上
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    View decorView = this.getWindow().getDecorView();
                    int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
                    decorView.setSystemUiVisibility(option);
                    this.getWindow().setStatusBarColor(Color.TRANSPARENT);
                }

                // versionCode > 4.4  and versionCode < 5.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                    this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                }
            }


        } else {
            /**
             * 无状态栏
             */
            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }


    }


    //==============================================================================================
    //==========================================================================打印日志和弹出框====
    //==============================================================================================

    /**
     * Toast
     *
     * @param text
     */
    public void showToast(String text) {
        if (!TextUtils.isEmpty(text)) {
            if (mToast == null) {
                mToast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
            }
            mToast.setText(text);
            mToast.show();
        }
    }

    /**
     * Toast
     *
     * @param text
     */
    public void showLongToast(String text) {
        if (!TextUtils.isEmpty(text)) {
            if (mToast == null) {
                mToast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG);
            }
            mToast.setText(text);
            mToast.show();
        }
    }

    /**
     * Toast
     *
     * @param resId
     */
    public void showToast(int resId) {
        if (mToast == null) {
            mToast = Toast.makeText(getApplicationContext(), resId,
                    Toast.LENGTH_SHORT);
        } else {
            mToast.setText(resId);
        }
        mToast.show();
    }

    /**
     * Log
     *
     * @param msg
     */
    public static void showLog(String msg) {
        Log.e("调试日志======", msg);
    }


    //==============================================================================================
    //======================================================================BaseActivity常用方法====
    //==============================================================================================

    /**
     * 子类可以重写改变状态栏颜色
     */
//    protected int setStatusBarColor() {
//        return getColorPrimary();
//
//
//    }

    /**
     * 获取主题色
     */
    public int getColorPrimary() {
        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(R.attr.colorPrimaryDark, typedValue, true);
        return typedValue.data;
    }

    /**
     * 透明状态栏
     *
     * @return
     */
    protected boolean translucentStatusBar() {
        return false;
    }

    /**
     * 无状态栏
     *
     * @return
     */
    protected boolean noStatusBar() {
        return false;
    }

    /**
     * 沉静式状态栏
     *
     * @return
     */
    protected boolean calmStatusBar() {
        return true;
    }


    /**
     * 启动Activity
     */
    protected void startActivity(Class<?> clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
    }

    /**
     * findViewById
     *
     * @return View
     */
    protected <T extends View> T viewById(int viewId) {
        return (T) findViewById(viewId);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);

        LogUtil.e(this.getClass().getName() + "走到onDestroy，调用cancel方法");
        HttpUtils.cancel();

        unbinder.unbind();
        ActivityCollector.getInstance().finishActivity(this);

    }


    /**
     * 推送
     *
     * @param event
     */

    PushPopupUtils pushPopupUtils;
    NewDaYiConnectPopupUtil connectPopupUtil;

    @Subscriber(tag = EventBusTagUtils.MyApplication)
    public void fromMyApplication(Event event) {

        switch (event.getEventCode()) {

            case 1: {

                LogUtil.e("名字=====1" + className);
                LogUtil.e("名字=====2" + stackTopActivity.getClass().getName());

                if (className.equals(stackTopActivity.getClass().getName())) {
                    PushDetailBean pushDetailBean = (PushDetailBean) event.getData();
                    pushPopupUtils.updateData(pushDetailBean);
                    pushPopupUtils.showAnswerPopuPopu(this.getWindow().getDecorView());
                }

                break;
            }
            case 2: {

                if (className.equals(stackTopActivity.getClass().getName())) {
                    PushDetailBean pushDetailBean = (PushDetailBean) event.getData();
                    String rule = "计费方式:每" + pushDetailBean.getObj().getLive_billing_time()
                            + "分钟消费" + pushDetailBean.getObj().getLive_billing() + "兔币";
                    String money = "当前兔币:" + pushDetailBean.getObj().getAccount();

                    String content = "兔币不足即将退出直播间，请前往充值页面";

                    LiveCheckMoneyPopupUtils liveCheckMoneyPopupUtils = new LiveCheckMoneyPopupUtils(this);
                    liveCheckMoneyPopupUtils.setLiveCheckMoneyPopupUtilsListener(new LiveCheckMoneyPopupUtils.LiveCheckMoneyPopupUtilsListener() {
                        @Override
                        public void onCancle() {

                            //取消就退出直播间通过EventBus进行处理
                            EventBus.getDefault().post(new Event<>(1, ""), EventBusTagUtils.BaseActivity);
                        }

                        @Override
                        public void onSure() {

                            //确认进入

                            EventBus.getDefault().post(new Event<>(2, ""), EventBusTagUtils.BaseActivity);

                        }
                    });
                    liveCheckMoneyPopupUtils.setContent(content);
                    liveCheckMoneyPopupUtils.showAnswerPopuPopu(this.getWindow().getDecorView(), rule, money);


                }

                break;
            }

            case 3:
                //如果当前栈顶的activity是寻找问题activity,就进入老师回答详情界面
                if (stackTopActivity.getClass().getName().equals("com.dayi.activity.AskQuestionFindActivity")) {

                    PushDetailBean pushDetailBean = new PushDetailBean();
                    pushDetailBean = (PushDetailBean) event.getData();

                    ARouter.getInstance().build(ARouterPathUtils.Dayi_TeacherAnswerDetailActivity)
                            .withString("replyId", pushDetailBean.getObj().getReply_id() + "").navigation();
                }
                break;
            case 4:
                //老师退出直播间
                if (stackTopActivity.getClass().getName().equals("com.live.activity.MainRoomActivity")) {

                    EventBus.getDefault().post(new Event<>(4, ""), EventBusTagUtils.BaseActivity);

                }
                break;
            case 7:
                //学生收到老师直播间的邀请

                LogUtil.e("名字=====1" + className);
                LogUtil.e("名字=====2" + stackTopActivity.getClass().getName());

                if (className.equals(stackTopActivity.getClass().getName())) {
                    PushDetailBean pushDetailBean = (PushDetailBean) event.getData();
                    connectPopupUtil.updateData(pushDetailBean);
                    connectPopupUtil.showAnswerPopuPopu(this.getWindow().getDecorView());
                }
                break;
            case 8:
                ////老师辅导学生做作业，邀请学生进入作业辅导直播间

                LogUtil.e("名字=====1" + className);
                LogUtil.e("名字=====2" + stackTopActivity.getClass().getName());

                if (className.equals(stackTopActivity.getClass().getName())) {
                    PushDetailBean pushDetailBean = (PushDetailBean) event.getData();
                    connectPopupUtil.updateData(pushDetailBean);
                    connectPopupUtil.showAnswerPopuPopu(this.getWindow().getDecorView());
                }
                break;
        }


    }

    /**
     * 监听Activity的生命周期
     */

    private Activity stackTopActivity;

    private void initActivityLife() {
        pushPopupUtils = new PushPopupUtils(this);
        connectPopupUtil = new NewDaYiConnectPopupUtil(this);

        className = this.getClass().getName();

        MyApplication.getInstance().registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

                ///全局禁止竖屏
//                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }

            @Override
            public void onActivityStarted(Activity activity) {


            }

            @Override
            public void onActivityResumed(Activity activity) {
                stackTopActivity = activity;

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });

    }

}
